package cn.finder.datatunnel;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

import cn.finder.datatunnel.processor.DataChannel;
import cn.finder.datatunnel.processor.TcpDataChannel;
import cn.finder.datatunnel.processor.UdpDataChannel;

public class DTUtils {

	/***
	 * 流转字节数组
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public static byte[] streamToBytes(InputStream is) throws IOException{
		
		String dt_client_readdata_endmark=DTConfig.dt_client_readdata_endmark;
		
		if("mark".equalsIgnoreCase(dt_client_readdata_endmark)){
			byte dt_client_readdata_mark=Byte.valueOf(DTConfig.dt_client_readdata_mark).byteValue();
			byte[] b=new byte[1];
			
			ByteArrayOutputStream baos=new ByteArrayOutputStream();
			
			int pos=-1;
			while((pos=is.read(b, 0, b.length))!=-1){
				baos.write(b, 0, pos);
				if(b[0]==dt_client_readdata_mark){
					break;
				}
			}
			
			return baos.toByteArray();
		}
		else if("size".equalsIgnoreCase(dt_client_readdata_endmark)){
			int dt_client_readdata_size=Integer.valueOf(DTConfig.dt_client_readdata_size).intValue();
			
			byte[] b=new byte[1];
			
			ByteArrayOutputStream baos=new ByteArrayOutputStream();
			
			int pos=-1;
			while((pos=is.read(b, 0, b.length))!=-1){
				baos.write(b, 0, pos);
				if(baos.size()==dt_client_readdata_size){
					break;
				}
				
			}
			
			return baos.toByteArray();
		}
		
		return null;
		
		
	}
	
	/***
	 * 从 UDP数据包中读取
	 * @param socket
	 * @return
	 * @throws IOException
	 */
	public static byte[] readToBytes(DatagramSocket socket) throws IOException{
		
            
        String dt_client_readdata_endmark=DTConfig.dt_client_readdata_endmark;
		
		if("mark".equalsIgnoreCase(dt_client_readdata_endmark)){
			byte dt_client_readdata_mark=Byte.valueOf(DTConfig.dt_client_readdata_mark).byteValue();
			
			int readdata_size=Integer.valueOf(DTConfig.dt_client_readdata_size);
			
			byte[] b=new byte[readdata_size];
			
			byte[] b_item=new byte[1];
			
			ByteArrayOutputStream baos=new ByteArrayOutputStream();
			
			DatagramPacket dataPacket = new DatagramPacket(b, b.length);
			int len=0;
			
			socket.receive(dataPacket);
			len=dataPacket.getLength();
			if(len>0){
				
				byte[] bytes=dataPacket.getData();
				
				for(int i=0;i<len;i++){
					b_item=new byte[]{bytes[i]};
					if(b_item[0]==dt_client_readdata_mark){
    					break;
    				}
					baos.write(b_item, 0, b_item.length);
				}
				
			}
			
			
			return baos.toByteArray();
		}
		else if("size".equalsIgnoreCase(dt_client_readdata_endmark)){
			int dt_client_readdata_size=Integer.valueOf(DTConfig.dt_client_readdata_size).intValue();
			byte[] b=new byte[dt_client_readdata_size];
			
			ByteArrayOutputStream baos=new ByteArrayOutputStream();
			
			
			DatagramPacket dataPacket = new DatagramPacket(b, b.length);
			int len=0;
			
			socket.receive(dataPacket);
			len=dataPacket.getLength();
			
			
			baos.write(dataPacket.getData(), 0, len);
			
			return baos.toByteArray();
		}
		
		return null;
		
	}
	
	
	/***
	 * 从通道中读取数据
	 * @param dataChannel
	 * @return
	 * @throws IOException
	 */
	public static byte[] readToBytes(DataChannel dataChannel) throws IOException{
		
		if(dataChannel instanceof TcpDataChannel){
			TcpDataChannel tcpDataChannel=(TcpDataChannel)dataChannel;
			InputStream is=tcpDataChannel.getChannel().getInputStream();
			
			return streamToBytes(is);
			
		}else if(dataChannel instanceof UdpDataChannel){
			UdpDataChannel udpDataChannel=(UdpDataChannel)dataChannel;
			
            
            String dt_client_readdata_endmark=DTConfig.dt_client_readdata_endmark;
    		
    		if("mark".equalsIgnoreCase(dt_client_readdata_endmark)){
    			//byte dt_client_readdata_mark=Byte.valueOf(DTConfig.dt_client_readdata_mark).byteValue();
    			
    			String dt_client_readdata_mark=DTConfig.dt_client_readdata_mark; //16进制字符串
    			
    			int readdata_size=Integer.valueOf(DTConfig.dt_client_readdata_size);
    			
    			byte[] b=new byte[readdata_size];
    			
    			
    			ByteArrayOutputStream baos=new ByteArrayOutputStream();
    			
    			/*DatagramPacket dataPacket = new DatagramPacket(b, b.length);
    			
    			
    			udpDataChannel.getChannel().receive(dataPacket);
    			
    			udpDataChannel.setDatagramPacket(dataPacket);*/
    			
    			DatagramPacket dataPacket=udpDataChannel.getDatagramPacket();
    			
    			int len=0;
				len=dataPacket.getLength();
				if(len>0){
					
					byte[] bytes=dataPacket.getData();
					
					for(int i=0;i<len;i++){
						byte current=bytes[i];
						String current_hexstr=bytesToHexString(new byte[]{current});
						if(current_hexstr.equalsIgnoreCase(dt_client_readdata_mark)){//使用16进制字符串比较
	    					break;
	    				}
						baos.write(new byte[]{bytes[i]}, 0, 1);
					}
					
				}
    			
    			
    			return baos.toByteArray();
    		}
    		else if("size".equalsIgnoreCase(dt_client_readdata_endmark)){
    			int dt_client_readdata_size=Integer.valueOf(DTConfig.dt_client_readdata_size).intValue();
    			byte[] b=new byte[dt_client_readdata_size];
    			
    			ByteArrayOutputStream baos=new ByteArrayOutputStream();
    			
    			
    			DatagramPacket dataPacket =udpDataChannel.getDatagramPacket();;
    			
    			int len=0;
    			
				len=dataPacket.getLength();
				
    			
				baos.write(dataPacket.getData(), 0, len);
				
    			return baos.toByteArray();
    		}
    		
    		return null;
		}
		
		
		return null;
		
		
	}
	
	
	
	
	/** 
	 * Convert byte[] to hex string.这里我们可以将byte转换成int，然后利用Integer.toHexString(int)来转换成16进制字符串。 
	 * @param src byte[] data 
	 * @return hex string 
	 */     
	public static String bytesToHexString(byte[] src){  
	    StringBuilder stringBuilder = new StringBuilder("");  
	    if (src == null || src.length <= 0) {  
	        return null;  
	    }  
	    for (int i = 0; i < src.length; i++) {  
	        int v = src[i] & 0xFF;  
	        String hv = Integer.toHexString(v);  
	        if (hv.length() < 2) {  
	            stringBuilder.append(0);  
	        }  
	        stringBuilder.append(hv);  
	    }  
	    return stringBuilder.toString();  
	}  
	/** 
	 * Convert hex string to byte[] 
	 * @param hexString the hex string 
	 * @return byte[] 
	 */  
	public static byte[] hexStringToBytes(String hexString) {  
	    if (hexString == null || hexString.equals("")) {  
	        return null;  
	    }  
	    hexString = hexString.toUpperCase();  
	    int length = hexString.length() / 2;  
	    char[] hexChars = hexString.toCharArray();  
	    byte[] d = new byte[length];  
	    for (int i = 0; i < length; i++) {  
	        int pos = i * 2;  
	        d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));  
	    }  
	    return d;  
	}  
	
	/***
	 * 过滤 字节 为 0的
	 * @param data
	 * @return
	 */
	public static byte[] filterZeroBytes(byte[] data){
		ByteArrayOutputStream out=new ByteArrayOutputStream();
		
		for(int i=0;i<data.length;i++){
			byte current=data[i];
			if(current!=(byte)0){
				out.write(new byte[]{current}, 0, 1);
			}
			
		}
		return out.toByteArray();
		
	}
	/** 
	 * Convert char to byte 
	 * @param c char 
	 * @return byte 
	 */  
	private static byte charToByte(char c) {  
	    return (byte) "0123456789ABCDEF".indexOf(c);  
	}
}
